<template>
  <div class="infinite-container">
    <select-role2 v-if="!isModify" @familychang="selperson" :needCertificate="0" ref="childRole"></select-role2>
    <div class="infinite-container" style="padding-bottom: 45px;">
      <div class="greenTop">
        <div class="select-role flex flex_between">
          <div class="roleLeft flex flex_vcenter">
            <i class="w-icon w-icon-icon_common_jzr2 v-middle inline-block"></i>
            <span class="ml10 f16">就诊人</span>
          </div>
          <div class="roleRight flex flex_vcenter" @click="showSelPerson">
            <span :class="{mr10: isModify}">{{familyPerson.realname}}</span>
            <!-- <span class="centerT">{{familyPerson.sexcode | getSex}}</span> -->
            <!-- <span>{{familyPerson.birthdate | getAge}}岁</span> -->
            <i class="iconfont icon-small-arrow-right t9" v-if="!isModify"/>
          </div>
        </div>
      </div>
      <div>
        <ul class="topList">
          <li class="flex flex_between flex_vcenter">
            <span class="label">
              药品名称
              <i class="point"></i>
            </span>
            <input
              class="maxlen"
              type="text"
              maxlength="20"
              name="drugName"
              placeholder="输入药品名称"
              v-model="drugName"
            />
          </li>
          <li class="flex flex_between flex_vcenter">
            <span class="label">用法</span>
            <input type="text" maxlength="5" placeholder="选填，如口服" v-model="useMethod" />
          </li>
          <li class="flex flex_between flex_vcenter">
            <span class="label">用量</span>
            <input type="text" maxlength="5" placeholder="选填（如1片）" v-model="useAmount" />
          </li>
        </ul>
        <div>
          <ul class="topList">
            <li class="flex flex_between flex_vcenter">
              <span class="label">
                提醒日期
                <i class="point"></i>
              </span>
              <!-- <mu-date-picker hintText="选择用药日期" v-model="drugDate" :minDate="new Date()" /> -->
              <div>
                <span class="pr10" @click="showDatePicker('start')">{{drugStartDate || '请选择开始日期'}}</span>至
                <span class="pl10" @click="showDatePicker('end')">{{drugEndDate || '请选择结束日期'}}</span>
              </div>
            </li>
            <li class="flex flex_between flex_vcenter">
              <span class="label">
                提醒频次
                <i class="point"></i>
              </span>
              <selector2
                :options="UES_RATE"
                wrapClass="text-right"
                @selectchange="handleRateChange"
                label="rateName"
                :defaultValue="useRate"
              ></selector2>
            </li>
            <li class="flex flex_between flex_vcenter" v-if="chooseRate && chooseRate.rateDay > 1">
              <span class="label">
                周期日
                <i class="point"></i>
              </span>
            </li>
            <ul class="remindTimesList" v-if="chooseRate && chooseRate.rateDay > 1">
              <li 
                class="flex flex_between flex_vcenter"
                v-for="(value, index) in remindDayList"
                :key="index"
              >
                <span>第{{index + 1}}次提醒周期日</span>
                <div class="flex flex_vcenter">
                  <selector2
                    :options="rateDayArr"
                    wrapClass="text-right"
                    @selectchange="handleWeekChange(index, $event)"
                    label="label"
                    :defaultValue="value | filterDay"
                  ></selector2>
                </div>
              </li>
            </ul>
            <li class="flex flex_between flex_vcenter" v-if="remindTimesList && remindTimesList.length > 0">
              <span class="label">
                提醒次数
                <i class="point"></i>
              </span>
              <!-- <div @click="addReminderTime()">
                <span>增加次数</span>
                <img src="../../assets/images/ic_add.png" alt class="addIcon" />
              </div> -->
            </li>
            <ul class="remindTimesList" v-if="remindTimesList && remindTimesList.length > 0">
              <li
                class="flex flex_between flex_vcenter"
                style="padding-right: 15px;"
                v-for="(value, index) in remindTimesList"
                :key="index"
              >
                <span>第{{index + 1}}次提醒时间</span>
                <div class="flex flex_vcenter flex_right" style="min-width: 100px;" @click="selectTime(index)">
                  <span v-if="value && value.hour && value.min">{{value.hour}}:{{value.min}}</span>
                  <span v-else class="pl10"></span>
                  <i class="iconfont icon-small-arrow-right"/>
                </div>
              </li>
            </ul>
          </ul>
        </div>
        <ul class="topList">
          <li class="flex flex_between flex_vcenter">
            <span class="label">
              消息推送
              <i class="point"></i>
            </span>
            <div>
              <mu-switch v-model="pushFlag" />
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="opera-btn">
      <mu-raised-button label="保存" class="submit-btn btn" fullWidth primary @click="submitAdd()" />
    </div>
    <mu-dialog :open="timePickerDialog" @close="closetimePicker">
      <timePicker
        :address="defaltTime"
        @closeDialog="closetimePicker"
        @confirmSelectTime="confirmSelectTime"
      ></timePicker>
    </mu-dialog>
  </div>
</template>

<script>
import Selector2 from "../../components/Selector2";
import SelectRole2 from "../../components/SelectRole2.vue";
import timePicker from "../../components/BsTimePicker.vue";
import { commonAjaxJson, RESTFUL_API } from "../../api/api";
export default {
  components: { Selector2, SelectRole2, timePicker },
  data() {
    return {
      hospitalCode: sessionStorage.getItem("hospitalCode") || "",
      familyPerson: JSON.parse(sessionStorage.getItem("familyPerson")) || {},
      isModify: false,
      drugStartDate: "",
      drugEndDate: "",
      UES_RATE: [],
      useRate: "",
      chooseRate: {},
      reminderId: "",
      drugName: "",
      useMethod: "",
      useAmount: "",
      currentTimeIndex: "",
      rateDayArr: [],
      remindDayList: [],
      remindTimesList: [],
      defaltTime: ['12', '00'],
      timePickerDialog: false,
      pushFlag: true,
    };
  },
  filters: {
    filterDay (val){
      return `第${val}日`
    }
  },
  mounted (){
    this.getUseRate();
    this.getTakeWay();
    if (this.$route.query.reminderItem) {
      this.isModify = true
      let reminderDetail = JSON.parse(this.$route.query.reminderItem)
      this.familyPerson = {
        realname: reminderDetail.userName,
        id: reminderDetail.fid
      }
      this.reminderId = reminderDetail.reminderId;
      this.drugName = reminderDetail.drugName;
      this.useMethod = reminderDetail.takeWay;
      this.useAmount = reminderDetail.dosage;
      this.drugStartDate = reminderDetail.startTime
      this.drugEndDate = reminderDetail.endTime
      this.useRate = reminderDetail.rateName
      this.chooseRate.rateDay = reminderDetail.cycle
      this.chooseRate.rateCode = reminderDetail.useMethod
      this.chooseRate.rateName = reminderDetail.rateName
      this.chooseRate.rateTimes = reminderDetail.times
      this.pushFlag = reminderDetail.pushFlag === 0 ? true : false
      let rateDayArr = []
      for(let j = 1; j <= reminderDetail.cycle; j++) {
        rateDayArr.push({label: `第${j}日`, value: String(j)})
      }
      this.rateDayArr = rateDayArr
      reminderDetail.reminderTimeArr.forEach(v => {
        if(reminderDetail.cycle > 1) {
          this.remindDayList.push(v.split("#")[0])
          this.remindTimesList.push({hour: (v.split("#")[1]).split(":")[0], min: (v.split("#")[1]).split(":")[1]})
        } else {
          this.remindTimesList.push({hour: v.split(":")[0], min: v.split(":")[1]})
        }
      })
      
    }
  },
  methods: {
    showSelPerson() {
      if(this.isModify) return
      this.$refs.childRole.show();
    },
    selperson(val) {
      this.familyPerson = val;
      sessionStorage.familyPerson = JSON.stringify(val);
    },
    getUseRate() {
      commonAjaxJson(RESTFUL_API.getUseRate, {hospitalCode: this.hospitalCode}, true).then(res => {
        if(res.data.code == 200) {
          res.data.data.map(v => {
            if(v.rateDay > 1) {
              let rateDayArr = []
              for(let j = 1; j <= v.rateDay; j++) {
                rateDayArr.push({label: `第${j}日`, value: String(j)})
              }
              v.rateCycleArr = v.rateCycle.split(",")
              v.rateDayArr = rateDayArr
            }
          })
          this.UES_RATE = res.data.data
        }
      })
    },
    getTakeWay() {
      commonAjaxJson(RESTFUL_API.getTakeWay, {hospitalCode: this.hospitalCode}, true).then(res => {
        if(res.data.code == 200) {
          this.TAKE_WAY = res.data.data
        }
      })
    },
    queryRemindDetail() {
      //未使用
      let param = {
        reminderId: this.reminderId
      };
      commonAjaxJson(RESTFUL_API.reminderDetail, param, true).then(res => {
        if (res.data.code == 200) {
          let result = res.data.data;
          this.drugName = result.drugName;
          this.useMethod = result.takeWay;
          this.useAmount = result.dosage;
          this.activeRemindIndex = result.useMethod - 1;
          this.familyPerson.realname = result.userName;
          this.familyPerson.id = result.fid;
          this.pushFlag = result.pushFlag == 0;
          // if (result.useMethod - 1 == 0) {
          //   // 每日提醒
          //   let Arr = result.reminderTime.split(",");
          //   for (let i = 0; i < Arr.length; i++) {
          //     this.remindTimesList.push({
          //       hour: Arr[i].split(":")[0],
          //       min: Arr[i].split(":")[1]
          //     });
          //   }
          // } else {
          //   // 一次性
          //   this.drugDate = result.reminderTime.slice(0, 10);
          //   this.onlyOneSelectedTime = result.reminderTime.slice(11, 16);
          // }
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: res.data.message
          });
        }
      });
    },
    handleTakeWayChange(v) {
      this.takeWay = v.wayName;
    },
    handleRateChange(v) {
      this.chooseRate = v;
      this.useRate = v.rateName;
      this.remindTimesList = [];
      this.rateDayArr = v.rateDayArr || [];
      this.remindDayList = v.rateCycleArr || [];
      v.rateHisTime.split(",").forEach((val, index) => {
        this.remindTimesList.push({hour: val.split(":")[0], min: val.split(":")[1]})
      })
    },
    handleWeekChange(index, v) {
      this.remindDayList[index] = v.value
    },
    confirmSelectTime(time) {
      this.remindTimesList[this.currentTimeIndex].hour = time[0];
      this.remindTimesList[this.currentTimeIndex].min = time[1];
      this.timePickerDialog = false;
    },
    closetimePicker() {
      this.timePickerDialog = false;
    },
    selectTime(index) {
      // 修改某一条提醒时间
      this.currentTimeIndex = index;
      this.timePickerDialog = true;
      let cur = this.remindTimesList[this.currentTimeIndex];
      let d = new Date();
      let hour = d.getHours();
      let min = d.getMinutes();
      if (!cur.hour && cur.hour != "00") {
        cur.hour = hour < 10 ? "0" + hour : "" + hour;
        cur.min = min < 10 ? "0" + min : "" + min;
      }
      this.defaltTime = [cur.hour, cur.min];
    },
    showDatePicker(type) {
      this.$picker.show({
        date:
          type === "start"
            ? this.drugStartDate
            : type === "end"
            ? this.drugEndDate
            : "",
        succeed: e => {
          if (type === "start") {
            let drugStartDate = e;
            if (
              !!this.drugEndDate &&
              new Date(drugStartDate).getTime() >
                new Date(this.drugEndDate).getTime()
            ) {
              this.$store.commit("UPDATE_TOAST", {
                message: "开始时间须小于结束时间"
              });
              return;
            }
            this.drugStartDate = e;
          } else if (type === "end") {
            let drugEndDate = e;
            if (
              !!this.drugStartDate &&
              new Date(this.drugStartDate).getTime() >
                new Date(drugEndDate).getTime()
            ) {
              this.$store.commit("UPDATE_TOAST", {
                message: "开始时间须小于结束时间"
              });
              return;
            }
            this.drugEndDate = e;
          }
        }
      });
    },

    submitAdd (){
      if (!this.drugName) {
        this.$store.commit("UPDATE_TOAST", {
          message: "请输入药品名称"
        });
        return;
      }
      if(!this.drugStartDate || !this.drugEndDate) {
        this.$store.commit("UPDATE_TOAST", {
          message: "请选择提醒日期"
        });
        return;
      }
      if(!this.useRate || this.useRate == "") {
        this.$store.commit("UPDATE_TOAST", {
          message: "请选择提醒频次"
        });
        return;
      }
      let param = {
        fid: this.familyPerson.id,
        drugId: "",
        drugName: this.drugName,
        takeWay: this.useMethod,
        startTime: this.drugStartDate,
        endTime: this.drugEndDate,
        useMethod: this.chooseRate.rateCode,
        rateName: this.chooseRate.rateName,
        cycle: this.chooseRate.rateDay, //是否为rateDay?
        dosage: this.useAmount,
        times: this.chooseRate.rateTimes,
        reminderTime: "",
        pushFlag: this.pushFlag ? 0 : 1
      };
      let timesArray = [];
      if(this.chooseRate.rateDay > 1) {
        for (let i = 0; i < this.remindTimesList.length; i++) {
          if ( this.remindTimesList[i].hour != "" && this.remindTimesList[i].min != "" ) {
            timesArray.push(
              this.remindDayList[i] + "#" + this.remindTimesList[i].hour + ":" + this.remindTimesList[i].min
            );
          }
        }
        param.reminderTime = timesArray.join(",")
      } else {
        for (let i = 0; i < this.remindTimesList.length; i++) {
          if ( this.remindTimesList[i].hour != "" && this.remindTimesList[i].min != "" ) {
            timesArray.push(
              this.remindTimesList[i].hour + ":" + this.remindTimesList[i].min
            );
          }
        }
        param.reminderTime = timesArray.join(",")
      }
      let requestUrl = "";
      if (this.reminderId) {
        // 修改用药提醒
        requestUrl = "reminderUpdate";
        param.reminderId = this.reminderId;
      } else {
        // 新增用药提醒
        requestUrl = "addReminder";
      }
      commonAjaxJson(RESTFUL_API[requestUrl], param, true).then(res => {
        if (res.data.code == 200) {
          this.$store.commit("UPDATE_TOAST", {
            message: "保存成功",
            fn: () => {
              // this.$router.push({
              //   path: "/drugReminder/index"
              // });
              this.$router.go(-1)
            }
          });
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: res.data.message
          });
        }
      });
    }
    
  }
};
</script>

<style lang="less" scoped>
@import "../../common/css/component";
.maxlen {
  white-space: nowrap;
}
.topList {
  background-color: white;
  margin-top: 10px;
  > li {
    margin-left: 10px;
    border-bottom: 1px solid @color-border;
    padding: 10px;
  }
  input {
    border: none;
    outline: none;
    width: 180px;
    text-align: right;
  }
}
.point {
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: red;
  margin-bottom: 4px;
}
.doubleBtn {
  width: 120px;
  border: 1px solid @color-primary;
  color: @color-primary;
  border-radius: 5px;
  > div {
    width: 60px;
    text-align: center;
    padding: 4px 0;
  }
  .activeOne {
    background-color: @color-primary;
    color: white;
  }
}
.everyDayBox {
  background-color: white;
  > div {
    margin-left: 10px;
    border-bottom: 1px solid @color-border;
    padding: 10px;
  }
}
.addIcon {
  width: 20px;
  vertical-align: bottom;
}
.remindTimesList {
  > li {
    margin-left: 24px;
    border-bottom: 1px solid @color-border;
    padding: 10px;
    img {
      height: 16px;
      margin-left: 5px;
    }
  }
}
.onlyOneBox {
  > ul {
    margin-top: 0;
  }
}
.centerT {
  padding: 0 5px;
}
.opera-btn {
  position: absolute;
  bottom: 0;
  width: 100%;
  z-index: 9;
}
</style>